/* eslint-disable react-hooks/exhaustive-deps */
import React,{useEffect,useState} from 'react'
import Header from "../../components/Header"
import { Tabs, InfiniteScroll,PullToRefresh } from 'antd-mobile'
import {getList} from "../../api"
import { sleep } from 'antd-mobile/es/utils/sleep'
import "./style.scss"

function Index() {
    const [keys,setKeys]:any =useState(0)
    const [page,setPage]=useState(1)
    const [list,setList]:any=useState([])
    const [flag,setFlag]=useState(true)
    const [hasMore,setHasMore]:any=useState(true)
    const tabs=[
        '关注',
        '发现',
        '深圳'
    ]
    interface respType{
        code?:number,
        data:any[],
        total?:number
    }
    const changeKey=(key:any)=>{
        setKeys(key)
    }
    const getAndSet =async()=>{
        const resp:respType=await getList({keys:keys,page:page})
        console.log(resp.total,resp.data.length)
        setList(resp.data)
        if(resp.total===resp.data?.length){
            setHasMore(false)
        }
        setFlag(true)
    }
    useEffect(() => {
        getAndSet()
    }, [keys])
    const loadMore=async()=>{
        if(flag){
            setFlag(false)
            await setPage(page+1)
            await getAndSet()
        }
    }
    return (
        <div className='moreWrap'>
            <Header></Header>
            <div className="title">
                <Tabs defaultActiveKey={keys} onChange={(key)=>changeKey(key)}>
                    {
                        tabs.map((v,i)=>{
                            return(
                                <Tabs.Tab title={v} key={i}>
                                </Tabs.Tab>
                            )
                        })
                    }
                </Tabs>
            </div>
            <div className="listWrap">
            <PullToRefresh
                onRefresh={async () => {
                    await sleep(1000)
                    window.location.reload()
                }}
                >
                    {
                    list&&list.length&&list.map((v:any,i:any)=>{
                        return(
                            <dl key={i}>
                                <dt><img src={v.url} alt="" /></dt>
                                <dd>{v.title}</dd>
                            </dl>
                        )
                    })
                }
                {
                    list&&list.length&&<InfiniteScroll loadMore={()=>loadMore()} hasMore={hasMore} />
                }
                </PullToRefresh>
                
            </div>
        </div>
    )
}

export default Index
